<template>
  <div class="relative" >
    <audio
      ref="audio"
      :src="src"
      @play="auidoPlay($event)"
      @pause="auidoPause($event)"
      @canplaythrough="audioLoad($event)"
      @timeupdate="handleTimeUpdate($event)"
    />
    <div class="audioStyle" >
      <img class="img1" src="../../assets/images/aplay.png" alt="">
      <span style="padding-left: 10px; padding-right: 10px; font-size: 14px;">{{ currentTime }}/{{ audioDuration }}</span>
      <img class="img2" :class="{'hidden' : !isPlay }" src="../../assets/images/play1.png" @click="handleAudioPlay">
    </div>
  </div>
</template>

<script>
export default {
  props: {
    src: {
      type: String,
      default: ''
    },
  },
  data() {
    return {
      isPlay: true,
      currentTime: '00:00',
      audioDuration: '00:00',
      loadState: false,
    }
  },
  methods: {
    load(type) {
      if (this.loadState)
          return;
      this.loadState = true;
      this.$emit("load", type);
    },
    audioLoad(e) {
      const audioElement = this.$refs.audio;
      if (audioElement) {
        this.audioDuration = this.formatDuration(audioElement.duration);
      }
      this.load('audio')
    },
    auidoPlay(e) {
      this.isPlay = true;
    },
    auidoPause(e) {
      this.isPlay = true;
    },
    handleAudioPlay(e) {
      this.$refs.audio.play();
    },
    handleTimeUpdate(e) {
      const audioElement = this.$refs.audio;
      if (audioElement) {
        this.currentTime = this.formatDuration(audioElement.currentTime);
      }
    },
    formatDuration(duration) {
      const minutes = Math.floor(duration / 60);
      const seconds = Math.floor(duration % 60);
      return `${this.padNumber(minutes)}:${this.padNumber(seconds)}`;
    },
    padNumber(num) {
      return num.toString().padStart(2, '0');
    },
  },
}
</script>
<style scoped>
.audioStyle {
  display: flex; flex-direction: row; align-items: center;
}
.img1 {
  width: 126px; height: 16px;
}
.img2 {
  width: 32px; height: 32px;
}
.relative {
  position: relative;
  width: 100%;
  height: 100%;
}
.hidden {
  display: none;
}
</style>